# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/1/30
# python-version    : Python 3.7.0
# description       : Redis 缓存

import redis, os
from com.articles.microapp.config.config import CONFIG
from com.articles.microapp.utils.constants import CommonConstants as consts
from com.articles.microapp.utils.db_utils import DbUtils
from com.articles.microapp.entities.type import Type
from com.articles.microapp.entities.tag import Tag
from com.articles.microapp.entities.user import User
import com.articles.microapp.utils.dict_utils as DictUtil
from com.articles.microapp.utils.string_utils import String
from com.articles.microapp.utils.logger_utils import Logger
from com.articles.microapp.utils.xml_utils import XMLParser

config = CONFIG.config()
logger = Logger()
parser = XMLParser(file=os.path.dirname(os.path.realpath(__file__)) + '\\cache_sql.xml')


class Cache(object):
    """
    缓存工具类
    """
    __pool = redis.ConnectionPool(host=config.get_value(consts.CACHE_SECTION, consts.CACHE_HOST),
                                  port=int(config.get_value(consts.CACHE_SECTION, consts.CACHE_PORT)),
                                  decode_responses=bool(
                                      config.get_value(consts.CACHE_SECTION, consts.CACHE_DECODE_RESPONSES)))

    def __init__(self):
        self.__redis = redis.Redis(connection_pool=self.__pool)

    def get(self, key):
        return self.__redis.get(key)

    def set(self, key, value, expire=None):
        if isinstance(value, dict):
            self.__redis.set(key, ''.join(str(value)), ex=expire)
        else:
            self.__redis.set(key, value, ex=expire)

    def get_type(self, key):
        """
        从缓存中获取文章类型 \n
        :param key: 类型ID
        :return: Type()
        """
        try:
            # 组装key
            cache_id = consts.CACHE_TYPE + str(key)
            # 缓存中不存在，从数据库查询
            values = self.__redis.get(cache_id)
            if String.is_empty(values):
                db = DbUtils()
                sql = str.replace(parser.get_sql('getType'), '?', str(key))
                values = str(db.selectone(sql))
                # 将结果放入缓存
                self.__redis.set(cache_id, values)
            type_dict = DictUtil.str2dict(values)
            return Type(**type_dict)
        except Exception as e:
            logger.error('从缓存获取类型失败，%s', e)
            return None

    def get_tag(self, key):
        """
        从缓存中查询标签 \n
        :param key: 标签ID
        :return: Tag()
        """
        try:
            # 组装key
            cache_id = consts.CACHE_TAG + str(key)
            values = self.__redis.get(cache_id)
            # 缓存中不存在，从数据库查询
            if String.is_empty(values):
                db = DbUtils()
                sql = str.replace(parser.get_sql('getTag'), '?', str(key))
                values = str(db.selectone(sql))
                # 将结果放入缓存
                self.__redis.set(cache_id, values)
            tag_dict = DictUtil.str2dict(values)
            return Tag(**tag_dict)
        except Exception as e:
            logger.error('从缓存中获取标签失败，%s', e)
            return None

    def get_user(self, userid):
        """
        从缓存中查询用户 \n
        :param userid: 用户ID
        :return: User()
        """
        try:
            user = self.__redis.get(userid)
            if String.is_empty(user):
                db = DbUtils()
                sql = str.replace(parser.get_sql('getUser'), '?', userid)
                user = str(db.selectone(sql))
                self.__redis.set(userid, user)
            tag_dict = DictUtil.str2dict(user)
            return User(**tag_dict)
        except Exception as e:
            logger.error('从缓存中查询用户信息失败，%s', e)
            return None

if __name__ == '__main__':
    cache = Cache()
    print(cache.get('_wx_microapp_type_1'))
    print(cache.get_type('1'))